package ui {
import com.greensock.TweenLite;

import core.Facade;

import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;

import ru.cjay.loading.ResourceManager;

public class ShortMessagePopup {

    private static var _instance:ShortMessagePopup= null;
    private static var _allowInstantiation:Boolean = false;

    private var _mess:String;
    private var _timer:Timer;

    private var _ui:MovieClip;

    public static function getInstance():ShortMessagePopup{
        if (_instance == null){
            _allowInstantiation = true;
            _instance = new ShortMessagePopup();
            _allowInstantiation = false;
        }
        return _instance;
    }
    public function ShortMessagePopup() {
        if (!_allowInstantiation) {
            throw new Error("Error: Instantiation failed. Use ShortMessagePopup.getInstance instead of new.")
        }
        _timer = new Timer(7000,1);
        _timer.addEventListener(TimerEvent.TIMER_COMPLETE, function(){
            ShortMessagePopup.getInstance().hideMessage();
        });
        _ui =  new (ResourceManager.getInstance().getSwfAssetClass("ui:FlashPopup") as Class )();
        _ui.btn_close.addEventListener(MouseEvent.CLICK, function(event:MouseEvent){
            var popup = (event.currentTarget as SimpleButton);
            if (Facade.getInstance().stage.contains(popup.parent)){
                Facade.getInstance().stage.removeChild(popup.parent);
            }
        })


    }
    public function showMessage(message:String){
        _timer.start();
        _mess = message;
        if (Facade.getInstance().stage.contains(_ui)){
            TweenLite.to(_ui, 0.3,{alpha:0, onComplete: updateMessage});
        }else{
            updateMessage();
        }
    }
    public function hideMessage():void{
        if (Facade.getInstance().stage.contains(_ui)){
            TweenLite.to(_ui, 0.3,{alpha:0, y:_ui.y-20});
        }else{
        }
    }
    private function updateMessage():void{
        _ui.alpha = 0;
        _ui.message.text = _mess;
         _ui.message.multiline = true;
        _ui.message.wordWrap = true;
        _ui.message.autoSize = "left";
        _ui.message.width = 122;
        _ui.message.x = 5;
//        _ui.message.y = 5;
        _ui.back.height = _ui.message.height+10;
        _ui.back.y = 0;
        if (Facade.getInstance().stage.contains(_ui)){Facade.getInstance().stage.removeChild(_ui);}
        Facade.getInstance().stage.addChild(_ui);
        _ui.x = (Facade.WIDTH - _ui.width)/2;
        _ui.y =0;
        TweenLite.to(_ui,0.5,{alpha:1, y:30});
    }
}
}
